<script setup lang="ts">
import { ref, onBeforeUnmount, shallowRef } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { message } from "@/utils/message";
import { uploadImage, uploadVideo } from "@/api/sysupload";
import ReCol from "@/components/ReCol";
import Motion from "@/views/login/utils/motion";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: "",
    type: 1,
    title: "",
    logo: "",
    des: "",
    content: "",
    zt: 0,
    noticetime: "",
    orderby: 0,
    addtime: "",
    updatetime: ""
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadImage(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.alt, res.data.href);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadVideo(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.poster);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    }
  }
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

//
const fileList = ref([]);
if (newFormInline.value.logo) {
  const filename = newFormInline.value.logo.substring(
    newFormInline.value.logo.lastIndexOf("/") + 1
  );
  fileList.value = [{ name: filename, url: newFormInline.value.logo }];
} else {
  fileList.value = [];
}

const beforeUpload = async file => {
  const form = new FormData();
  form.append("file", file);
  if (newFormInline.value.type == 1) {
    uploadImage(form)
      .then(res => {
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          fileList.value = [{ name: res.data.alt, url: res.data.url }];
          newFormInline.value.logo = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  } else {
    uploadVideo(form)
      .then(res => {
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          const filename = res.data.url.substring(
            res.data.url.lastIndexOf("/") + 1
          );
          fileList.value = [{ name: filename, url: res.data.url }];
          newFormInline.value.logo = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  }
};

const beforeRemove = () => {
  fileList.value = [];
  newFormInline.value.logo = "";
  return false;
};
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="82px"
  >
    <el-row :gutter="30">
      <re-col :value="24" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="横幅名称" prop="title">
            <el-input
              type="textarea"
              v-model="newFormInline.title"
              clearable
              placeholder="请输入横幅名称"
            />
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="发布类型" prop="type">
            <el-radio-group v-model="newFormInline.type">
              <el-radio :label="1">图文</el-radio>
              <el-radio :label="2">视频</el-radio>
            </el-radio-group>
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="发布时间" prop="noticetime">
            <el-date-picker
              v-model="newFormInline.noticetime"
              type="date"
              placeholder="选择日期"
              format="YYYY 年 MM 月 DD 日"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="图片|视频" prop="logo">
            <el-upload
              action="upload"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              multiple
              :auto-upload="true"
              :file-list="fileList"
              :limit="1"
            >
              <el-button size="small" type="primary">上传文件</el-button>
            </el-upload>
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-image
            :src="newFormInline.logo"
            fit="contain"
            style="width: 200px; height: 200px"
          />
        </Motion>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="描述简介" prop="des">
            <el-input
              type="textarea"
              v-model="newFormInline.des"
              clearable
              placeholder="请输入描述简介"
            />
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="公告内容" prop="content">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="width: 100%; height: 300px; overflow-y: hidden"
              v-model="newFormInline.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="排序" prop="orderby">
            <el-input
              v-model="newFormInline.orderby"
              clearable
              placeholder="请输入排序"
              :style="{ width: '220px' }"
            />
          </el-form-item>
        </Motion>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <Motion>
          <el-form-item label="状态" prop="zt">
            <el-radio-group v-model="newFormInline.zt">
              <el-radio :label="0">待发布</el-radio>
              <el-radio :label="1">已发布</el-radio>
            </el-radio-group>
          </el-form-item>
        </Motion>
      </re-col>
    </el-row>
  </el-form>
</template>
